package com.uxsino.commons.db.redis.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.uxsino.commons.db.redis.RedisKeys;
import com.uxsino.commons.db.redis.impl.AbstracStringtReadRedisRepostory;

/**
 * 描述：获取用户数据
 * 
 * 时间：2017年8月16日
 */
@Component
public class SiteUserRedis extends AbstracStringtReadRedisRepostory {

    private static final Logger LOG = LoggerFactory.getLogger(SiteUserRedis.class);

    @Override
    public String getRedisKey() {
        return RedisKeys.PATTEN_KEY_SITEUSER;
    }

    /**
     * 查询用户名
     * @param userId 用户ID
     * @return
     */
    public String getUserName(Long userId) {
        JSONObject userObj = getByUserId(userId);
        return userObj != null ? userObj.getString("userName") : null;
    }

    /**
     * 查询用户登录名
     * @param userId 用户ID
     * @return
     */
    public String getUserLoginName(Long userId) {
        JSONObject userObj = getByUserId(userId);
        return userObj != null ? userObj.getString("loginName") : null;
    }

    /**
     * 查询用户邮箱
     * @param userId 用户ID
     * @return
     */
    public String getUserEmail(Long userId) {
        JSONObject userObj = getByUserId(userId);
        return userObj != null ? userObj.getString("email") : null;
    }

    /**
     * 查询用户手机号
     * @param userId 用户ID
     * @return
     */
    public String getUserPhone(Long userId) {
        JSONObject userObj = getByUserId(userId);
        return userObj != null ? userObj.getString("phone") : null;
    }

    /**
     * 查询用户属性
     * @param id 用户ID
     * @param prop 字段属性
     * @return
     */
    public String prop(String id, String prop) {
        String u = this.get(id);
        if (StringUtils.isEmpty(u)) {
            return null;
        }
        try {
            JSONObject user = JSONObject.parseObject(u);
            return user.getString(prop);
        } catch (Exception e) {
            LOG.error("Get user from redis error: ", e);
            return null;
        }
    }

    /**
     * 用户名对应的用户信息
     * @return
     */
    public Map<String, JSONObject> loginNameMap() {
        List<String> users = this.getAll();
        if (users == null) {
            users = new ArrayList<>();
        }
        Map<String, JSONObject> map = new HashMap<>();
        users.forEach(str -> {
            try {
                JSONObject user = JSONObject.parseObject(str);
                if (user != null) {
                    map.put(user.getString("loginName"), user);
                }
            } catch (Exception e) {
                LOG.error("Get user from redis error: ", e);
            }
        });
        return map;
    }

    /**
     * 根据登录名查询用户
     * @param loginName 登录名
     * @return
     */
    public JSONObject getByLoginName(String loginName) {
        if (StringUtils.isEmpty(loginName)) {
            return null;
        }
        List<String> users = this.getAll();
        if (users == null) {
            users = new ArrayList<>();
        }
        for (String str : users) {
            try {
                JSONObject user = JSONObject.parseObject(str);
                if (loginName.equals(user.getString("loginName"))) {
                    return user;
                }
            } catch (Exception e) {
                LOG.error("Get user from redis error: ", e);
            }
        }
        return null;
    }

    /**
     * 根据用户名查询用户
     * @param userName 用户名
     * @return
     */
    public JSONObject getByUserName(String userName) {
        if (StringUtils.isEmpty(userName)) {
            return null;
        }
        List<String> users = this.getAll();
        if (users == null) {
            users = new ArrayList<>();
        }
        for (String str : users) {
            try {
                JSONObject user = JSONObject.parseObject(str);
                if (userName.equals(user.getString("userName"))) {
                    return user;
                }
            } catch (Exception e) {
                LOG.error("Get user from redis error: ", e);
            }
        }
        return null;
    }

    /**
     * 查询用户信息
     * @param userId 用户ID
     * @return
     */
    public JSONObject getByUserId(Long userId) {
        if (userId == null) {
            return null;
        }
        String user = get(userId + "");
        if (!StringUtils.isEmpty(user)) {
            JSONObject u = JSONObject.parseObject(user);
            return u;
        }
        return null;
    }

    /**
     * 根据编号查询用户
     * @param employeeCode 编号
     * @return
     */
    public JSONObject getByEmployeeCode(String employeeCode) {
        if (StringUtils.isEmpty(employeeCode)) {
            return null;
        }
        List<String> users = this.getAll();
        if (users == null) {
            users = new ArrayList<>();
        }
        for (String str : users) {
            try {
                JSONObject user = JSONObject.parseObject(str);
                if (employeeCode.equals(user.getString("employeeCode"))) {
                    return user;
                }
            } catch (Exception e) {
            }
        }
        return null;
    }

    public Long getOriginalUserId() {
        List<String> users = this.getAll();
        if (users != null && !users.isEmpty()) {
            for (String str : users) {
                try {
                    JSONObject user = JSONObject.parseObject(str);
                    if (user.getBooleanValue("original")) {
                        return user.getLongValue("id");
                    }
                } catch (Exception e) {
                }
            }
        }
        return null;
    }

    /**
     * 正则匹配查询用户
     * @param matcher 正则匹配
     * @return
     */
    public List<JSONObject> match(Pattern matcher) {
        List<String> users = this.getAll();
        if (users != null) {
            List<JSONObject> result = new ArrayList<>();
            result.addAll(users
                    .stream()
                    .map(itm -> {
                        try {
                            return JSON.parseObject(itm);
                        } catch (Exception e) {
                            LOG.error("解析错误", e);
                        }
                        return null;
                    })
                    .filter(itm -> itm != null
                            && (matcher.matcher(nullToEmpty(itm.getString("employeeCode").toLowerCase())).matches()
                            || matcher.matcher(nullToEmpty(itm.getString("userName").toLowerCase())).matches()))
                    .collect(Collectors.toList()));

            return result;
        }
        return null;
    }

    /**
     * null转换""
     * @param string 字符串
     * @return
     */
    private String nullToEmpty(String string) {
        return string == null ? "" : string;
    }

}
